<template>
  <div>
    <t-button size="small" @click="OnClick" theme="warning">
      <template #icon>
        <AddIcon/>
      </template>
      创建新的注册码
    </t-button>

    <t-drawer v-model:visible="data.show" header="创建新角色" :closeOnOverlayClick="false"
              :on-confirm="handleConfirm" @close="handleClose" size="large" destroy-on-close confirmBtn="确认创建">
      <div>
        <t-space direction="vertical" style="width: 100%;">
          <t-input-adornment prepend="权限角色">
            <t-select v-model="data.formData.role_id" size="large">
              <template v-for="it in data.formData.role_list">
                <t-option :value="it.id" :label="`${it.id} _ ${it.key} _ ${it.name}`"/>
              </template>
            </t-select>
          </t-input-adornment>
        </t-space>
      </div>
    </t-drawer>
  </div>
</template>
<script lang="ts" setup>
import {AddIcon} from "tdesign-icons-vue-next";
import {reactive} from "vue";
import api from "../../../../api/api";
import {MessagePlugin} from "tdesign-vue-next";
import {Role} from "../../../../tool/types";

const emits = defineEmits(['success'])
const data = reactive({
  show: false,
  formData: {
    role_id: 0,
    role_list: new Array<Role>(),
  }
})

const OnClick = async () => {
  data.show = true
  data.formData.role_id = 0
  let res = await api.Admin.User.GetAllRole()
  if (res != null) {
    data.formData.role_list = res.data
    if (data.formData.role_list.length > 0) {
      data.formData.role_id = data.formData.role_list[0].id
    }
  }
}

const handleClose = () => {
  data.show = false
}

const handleConfirm = async () => {
  let res = await api.Admin.Code.CreateCode({
    role_id: data.formData.role_id,
  })
  if (res != null) {
    data.show = false
    await MessagePlugin.success('创建成功')
    emits("success")
  }
}
</script>